/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

String.prototype.trim = function(){
	return this.replace(/(^\s*)|(\s*$)/g, "");
};

String.prototype.changeHtmlChar = function(){
	var rt = this.replace(/&/g, "&amp;");
	rt = rt.replace(/</g, "&lt;");
	rt = rt.replace(/>/g, "&gt;");
	rt = rt.replace(/\s/g, "&nbsp;");
	return rt;
};

//异步请求
var wdRequest = {
	wdXmlReq : null,
	wdCallback : null,
	wdTimer : -1,
	wdRtType : 2,//0:plain text, 1:xml data, 2:json data.

	cancelRequest : function(){
		if (this.wdXmlReq){
			this.wdXmlReq.abort();
			
			this.wdCallback = null;
			this.wdTimer = -1;
			this.wdRtType = 2;
		}
	},

	request : function(url, postParam, cb, rtType){
		if (this.wdXmlReq===null){
			if (window.XMLHttpRequest) this.wdXmlReq = new XMLHttpRequest();
			else if (window.ActiveXObject) this.wdXmlReq = new ActiveXObject("MSXML2.XMLHTTP.3.0");
		}
		
		if (this.wdXmlReq && this.wdCallback===null){
			this.wdCallback = cb;
			this.wdTimer = setTimeout("wdRequest.cancelRequest()", 60000);
			this.wdRtType = typeof(rtType)==='undefined' ? 2 : rtType;
			//onreadystatechange不能改变大小写
			this.wdXmlReq.onreadystatechange = function(){
				if (this.readyState===4){
					if (this.status===200 || this.status===0){
						var str = this.responseText.trim();
						if (str.length>0){
							if(wdRequest.wdRtType===0){//plain text
								wdRequest.wdCallback(str);
							}else if (wdRequest.wdRtType===1){//xml data
								wdRequest.wdCallback(this.responseXML);
							}else if (wdRequest.wdRtType===2){//json data
								var txt = str.changeHtmlChar();//转义特殊字符
								var json = null;
								
								try{
									json = eval("("+txt+")");
									if (json && json.error && json.error==="后台管理会话已过期"){
										top.location.href = "./login.php";
										json = null;
									}
								}catch(e){
									wdRequest.wdCallback({"error":"json语法无效："+str});
								}
								
								if (json!==null) wdRequest.wdCallback(json);
							}
						}else{
							wdRequest.wdCallback({"error":"错误：返回消息为空"});
						}
					}else if (wdRequest.wdRtType===2){//json data
						wdRequest.wdCallback({"error":"错误：返回码"+this.status+"，请重试"});
					}
					
					wdRequest.wdCallback = null;
					clearTimeout(wdRequest.wdTimer);
					wdRequest.wdTimer = -1;
					wdRequest.wdRtType = 2;
				}
			};

			if (postParam!==null){//POST方式，则加时间参数，取最新版本
				var p = url.indexOf("?");
				if (p>0) url += ("&rqtm="+(new Date()).getTime());
				else url += ("?rqtm="+(new Date()).getTime());
			}

			this.wdXmlReq.open(postParam===null ? "GET" : "POST", url, true);
			if (postParam!==null){
				//this.wdXmlReq.setRequestHeader("Content-Length", postParam.length);
				this.wdXmlReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
			}
			this.wdXmlReq.send(postParam);
		}
	}
};


